package org.kinglone.weixin.filter;

import java.io.PrintWriter;
import java.net.URLEncoder;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.kinglone.back.user.model.User;
import org.kinglone.weixin.model.WeixinFinalValue;
import org.kinglone.weixin.servlet.WeixinContext;
import org.springframework.web.servlet.handler.HandlerInterceptorAdapter;

public class WeixinAuthFilter extends HandlerInterceptorAdapter {

	@Override
	public boolean preHandle(HttpServletRequest request,HttpServletResponse response, Object handler) throws Exception {
		User tu = (User)request.getSession().getAttribute("user");
		System.out.println("----user:"+tu);
		if(tu == null){
							
			String path = "http://1n723r6757.iok.la/weixin/getCode.jspx";
			String uri = WeixinFinalValue.AUTH_URL;
			 uri = uri.replace("APPID", WeixinContext.getInstance().getAppId())
			   .replace("REDIRECT_URI",URLEncoder.encode(path, "UTF-8"))
			   .replace("SCOPE", "snsapi_userinfo")
			   .replace("STATE", "1");
			 System.out.println("uri:"+uri); 
			// req.getRequestDispatcher("/login.jsp").forward(req, resp);
			 StringBuffer pageCode=new StringBuffer();
			 pageCode.append("<script>window.location.href='"+uri+"';</script>");
			 response.setContentType("text/html;charset=utf-8");
			 PrintWriter out=response.getWriter();
			 out.println(pageCode.toString());
			 out.flush();
			 out.close();			
			return false;
		}else{
			return true;	
		}		 
				
	}
}
